# 用户相关逻辑
# 导入蓝图模块
from flask import Blueprint
from db import database,make_password
# 导入flask 基础的方法
from flask import request,jsonify
from db import database
import json
# 实例化蓝图对象
user = Blueprint("user",__name__)

# 注册接口
@user.route('/register/',methods=['POST','GET'])
async def register():
    data = json.loads(request.data)
    m_password = make_password(data['password'])

    sql = ("insert into `user`(`username`,`password`,`phone`) value('%s','%s','%s')" %(data['username'],m_password,data['phone']))
    print(sql)
    try:
        database.insert(sql)
        return {'code': 200, 'msg': '注册成功'}
    except:
        return {"code":10010,'msg':'用户已经存在'}

# 导入数据库中操作类
from db import Db,make_password

@user.route('/login/',methods=['GET',])
async def login():
    # 转换json类型
    # data = json.loads(request.data)
    # #接受参数
    # username = data['username']
    # password = data['password']

    username = request.args.get('username')
    password = request.args.get('password')

    #查询逻辑
    sql = "select * from `user` where username = '%s' and password = '%s'" %(username,make_password(password))
    print(sql)

    # 查询到用户
    res = database.get_one(sql)
    if res:
        return {'code':200,'id':res['id'],'username':res['username']}
    else:
        return {"code":403,'msg':'您的用户名或者密码错误'}

    # try:
    #     res = database.get_one(sql)
    # except:
    #     pass





